<template>
  <div class="fileGrabOrUpload-container">
    <van-nav-bar
      title="附件上传"
      left-arrow
      :border="false"
      @click-left="$router.back()"
    >
      <template #right> </template>
    </van-nav-bar>
    <van-row>
      <van-col span="12">
        <div class="upload_box">
          <van-field
            v-model="lastUploadFileNames"
            label="附件上传"
            readonly
            placeholder="请上传"
          />
          <van-uploader
            :max-count="1"
            :preview-image="false"
            :after-read="afterRead"
            :accept="acceptType"
            ref="uploaderRef"
          >
            <div class="btn">上传</div>
          </van-uploader>
        </div>
      </van-col>
      <van-col span="12">
        <div style="display: flex; align-items: center">
          <van-field
            readonly
            clickable
            name="picker"
            :value="currentFileName"
            label="已上传附件"
            placeholder="点击选择附件"
            @click="showPicker = true"
          />
          <div class="btn delete_btn" @click="handleDelete">删除</div>
        </div>
      </van-col>
    </van-row>
    <div v-autoHeight>
      <HPDFViewer v-if="showPdf" :path="pdfUrl"></HPDFViewer>
      <img v-else class="pdf-img" :src="pdfUrl" :alt="currentFileName" />
    </div>
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        v-model="selectedValues"
        :columns="columns"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
    <!-- 自定义文件属性 -->
    <van-popup
      v-model="showFilePopup"
      position="center"
      :close-on-click-overlay="false"
      style="width: 50vw"
      class="filePopup"
    >
      <div class="popup-header">附件上传属性</div>
      <div class="popup-content">
        <van-field
          v-model="newFileName"
          center
          clearable
          label="文件名"
          placeholder="请输入新的文件名"
        >
          <template #button>
            <div style="display: flex; gap: 0.1rem">
              <span>{{ currentUploadFileType }}</span>
              <van-button
                size="small"
                type="primary"
                @click="showFileNamePopup = true"
                >选择</van-button
              >
            </div>
          </template>
        </van-field>
				<van-field
          v-model="aboutBatchId"
          center
          clearable
          label="关联批次"
          placeholder="请输入关联批次"
        >
          <!-- <template #button>
            <div style="display: flex; gap: 0.1rem">
              <van-button
                size="small"
                type="primary"
                @click="showWatermarkTextPopup = true"
                >选择</van-button
              >
            </div>
          </template> -->
        </van-field>
        <van-field
          v-if="showWatermarkText"
          v-model="watermarkText"
          center
          clearable
          label="水印"
          placeholder="请输入水印"
        >
          <template #button>
            <div style="display: flex; gap: 0.1rem">
              <van-button
                size="small"
                type="primary"
                @click="showWatermarkTextPopup = true"
                >选择</van-button
              >
            </div>
          </template>
        </van-field>

        <div
          class="popup-content__footer"
          style="display: flex; justify-content: center"
        >
          <van-button
            native-type="button"
            type="default"
            block
            style="margin-right: 0.2rem"
            @click="handleFilePopupCancel"
            >取消</van-button
          >
          <van-button
            native-type="button"
            type="info"
            block
            @click="handleFilePopupConfirm"
            >确定</van-button
          >
        </div>
      </div>
    </van-popup>
    <van-popup
      v-model="showFileNamePopup"
      round
      position="bottom"
      :style="{ height: '50%' }"
    >
      <van-picker
        show-toolbar
        :columns="fileNameList"
        @cancel="showFileNamePopup = false"
        @confirm="onConfirmFileName"
      />
    </van-popup>
    <van-popup
      v-model="showWatermarkTextPopup"
      round
      position="bottom"
      :style="{ height: '50%' }"
    >
      <van-picker
        show-toolbar
        :columns="watermarkTextList"
        @cancel="showWatermarkTextPopup = false"
        @confirm="onConfirmWatermarkText"
      />
    </van-popup>
  </div>
</template>
<script>
import {
  Col,
  Row,
  Field,
  Uploader,
  Button,
  Popup,
  Picker,
  Image,
  NavBar,
  Notify,
} from "vant";
import {
  UploadRecordCorrelationFile,
  GetRecordCorrelationFiles,
  PreviewRecordCorrelationFile,
  DeleteRecordCorrelationFile,
} from "@/api/base";
import HPDFViewer from "@/components/HPDFViewer/index.vue";
export default {
  components: {
    [Col.name]: Col,
    [Row.name]: Row,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Image.name]: Image,
    [NavBar.name]: NavBar,
    HPDFViewer,
  },
  data() {
    return {
      showFileNamePopup: false,
      showWatermarkTextPopup: false,
      fileNameList: ["配制记录附页", "薄层鉴别附页"],
      watermarkTextList: ["鉴别1", "鉴别2", "鉴别3", "鉴别4"],
      showPdf: true,
			aboutBatchId: "",
      lastUploadFileNames: "",
      currentFile: "",
      currentFileName: "",
      pdfUrl: "",
      showPicker: false,
      columns: [],
      selectedValues: "",
      showFilePopup: false,
      newFileName: "配制记录附页",
      watermarkText: "鉴别1",
      currentUploadFileType: "",
      currentUploadFileInfo: "",
      showWatermarkText: false,
      acceptType:
        "image/jpeg, image/jpg, image/png, text/plain, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation ,application/pdf",
    };
  },
  computed: {
    pageParams() {
      return this.$store.state.pageParams;
    },
    fileNames() {
      return this.columns.map((item) => item.fileName).join(",");
    },
  },
  watch: {
    currentFile(val) {
      let currentFileInfo = this.columns.find((item) => item.value === val);
      if (currentFileInfo) this.previewFile(currentFileInfo.value);
    },
  },

  mounted() {
    console.log("this.pageParams", this.pageParams);
    this.GetRecordCorrelationFiles();
  },
  methods: {
    onConfirmFileName(val) {
      this.newFileName = val;
      this.showFileNamePopup = false;
    },
    onConfirmWatermarkText(val) {
      this.watermarkText = val;
      this.showWatermarkTextPopup = false;
    },
    handleDelete() {
      if (!this.columns.length) this.$toast("没有文件可以删除");
      this.$dialog
        .confirm({
          message: "确定删除吗？",
        })
        .then(() => {
          DeleteRecordCorrelationFile({
            Token: localStorage.getItem("tokenKey"),
            iautoid: this.currentFile,
          }).then((res) => {
            if (res.ErrorCode == 0) {
              this.$toast("删除成功");
              this.currentFile = "";
              this.currentFileName = "";
              this.pdfUrl = "";
              this.GetRecordCorrelationFiles();
            } else this.$toast(res.ErrorMsg);
          });
        });
    },
    onConfirm(item) {
      console.log("item", item);
      this.currentFile = item.value;
      this.currentFileName = item.text;
      this.showPicker = false;
    },
    async previewFile(iautoid) {
      const result = await PreviewRecordCorrelationFile({
        Token: localStorage.getItem("tokenKey"),
        iautoid,
      });
      // console.log(result);
      if (result.ErrorCode == 0) {
        let path = result.Result.targetPath;
        if (path) {
          let type = path.substring(path.lastIndexOf(".") + 1);
          console.log("type", this.pdfUrl);
          if (type == "pdf") {
            this.pdfUrl = result.Result.targetPath;
            this.showPdf = true;
          } else {
            let domain = localStorage.getItem("domain");
            this.pdfUrl = domain + result.Result.targetPath;
            this.showPdf = false;
          }
          console.log("state.path", this.pdfUrl);
          // alert('渲染pdf地址：'+ JSON.stringify(state.path));
        }
      }
    },
    async afterRead(files) {
      var fileName = files.file.name.substring(
        0,
        files.file.name.lastIndexOf(".")
      );
      var fileType = files.file.name.split(".").pop();
      const types = ["png", "jpg", "bmp", "jpeg"];
      this.currentUploadFileInfo = files;
      if (types.includes(fileType)) this.showWatermarkText = true;
      else this.showWatermarkText = false;
      // this.newFileName = fileName;
      this.currentUploadFileType = "." + fileType;
      // this.watermarkText = fileName;
			this.aboutBatchId = "";
      this.showFilePopup = true;
    },
    // 获取文件列表
    async GetRecordCorrelationFiles() {
      const result = await GetRecordCorrelationFiles({
        Token: localStorage.getItem("tokenKey"),
        ...this.pageParams,
      });
      console.log(result);
      if (result.ErrorCode == 0) {
        this.columns = result.Result.map((e) => ({
          text: `${e.Type=='About'?'(关联)':""} ${e.FileName}`,
          value: e.iautoid,
        }));
        console.log("this.columns", this.columns);
        // alert('获取文件列表' + JSON.stringify(result.result));
        if (!this.currentFileName) {
          this.currentFileName = this.columns[0]?.text;
          this.currentFile = this.columns[0]?.value;
        }
      }
    },
    handleFilePopupCancel() {
      this.newFileName = "配制记录附页";
      this.watermarkText = "鉴别1";
      this.currentUploadFileType = "";
      this.currentUploadFileInfo = "";
      this.showFilePopup = false;
    },
    async handleFilePopupConfirm() {
      let files = this.currentUploadFileInfo;
      if (!this.newFileName && this.showFilePopup) {
        return Notify({
          type: "warning",
          message: "请输入文件名",
        });
      }
      let param = new FormData(); //创建form对象
      if (files instanceof Array) {
        files.forEach((item) => {
          if (item.file) param.append("txt_file", item.file);
        });
      } else {
        files.file && param.append("txt_file", files.file);
      }
      param.append("Token", localStorage.getItem("tokenKey"));
      param.append("type", "TestPdf");
      param.append("batchId", this.pageParams.batchId);
      param.append("materialCode", this.pageParams.materialCode);
      param.append("recordCode", this.pageParams.recordCode);
      param.append("testId", this.pageParams.testId);
      param.append("fileName", this.newFileName);
      param.append("watermarkText", this.watermarkText);
      param.append("aboutBatchId", this.aboutBatchId);
      this.logFormData(param);
      this.$toast({
        message: "上传中...",
        forbidClick: true,
        duration: 0,
      });
      try {
        const result = await UploadRecordCorrelationFile(param);
        this.$toast.clear();
        if (result.ErrorCode == 0) {
          // debugger
          if (files instanceof Array) {
            files.forEach((item) => {
              item.status = "done";
            });
            this.lastUploadFileNames =
              files.map((item) => item.file.name) || "";
          } else {
            files.status = "done";
            this.lastUploadFileNames = this.newFileName;
          }
          this.$toast("上传文件成功");
          this.currentFile = "";
          this.currentFileName = "";
          this.pdfUrl = "";
          this.GetRecordCorrelationFiles();
          this.showFilePopup = false;
        }
      } catch (error) {
        this.$toast(error.ErrorMsg);
      }
    },
    logFormData(formData) {
      for (let [key, value] of formData.entries()) {
        console.log(key, value);
      }
    },
  },
};
</script>
<style lang='less' scoped>
.fileGrabOrUpload-container {
  .filePopup {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: auto !important;
    border-radius: 8px;
    .popup-header {
      font-size: 0.4rem;
      padding: 0.2rem;
      border-bottom: 1px solid #ccc;
    }
    .popup-content__footer {
      padding: 0.2rem;
    }
  }

  .upload_box {
    display: flex;
    align-items: center;
  }
  .btn {
    font-size: 0.3rem;
    border: 1px solid #ccc;
    width: 1rem;
    padding: 0.2rem;
    text-align: center;
    border-radius: 0.05rem;
    cursor: pointer;
  }
  .delete_btn {
    color: #fff;
    background: #ef3a3a;
    border: 1px solid red;
    margin-right: 10px;
  }
  .pdf-img {
    max-width: 100vw;
  }
}
</style>